"""
Event lifecycle and processing interfaces.

This module defines interfaces for the complete event processing pipeline,
middleware, and processor components.
"""

from abc import ABC, abstractmethod
from typing import (
    Any,
    List,
    Optional,
    TypeVar,
    Generic,
    Callable,
)

from continuallearning.events.core.event_types import BaseEventData

# Type variables
E = TypeVar("E", bound=BaseEventData)


# ========== Event Lifecycle Interfaces ==========


class EventProcessorInterface(ABC, Generic[E]):
    """
    Interface for complete event processing pipeline.

    This interface follows the Open-Closed Principle by allowing
    extension through composition of processors.
    """

    @abstractmethod
    def process_event(self, event: E) -> Optional[E]:
        """Process an event through the complete pipeline."""
        pass

    @abstractmethod
    def get_processing_stages(self) -> List[str]:
        """Get the names of processing stages in order."""
        pass


class EventMiddlewareInterface(ABC, Generic[E]):
    """
    Interface for event middleware that can wrap event processing.

    Middleware can perform operations before and after event processing,
    such as logging, timing, or error handling.
    """

    @abstractmethod
    def process(
        self, event: E, next_handler: Callable[[E], Optional[E]]
    ) -> Optional[E]:
        """
        Process an event with middleware logic.

        Args:
            event: The event to process
            next_handler: The next handler in the chain

        Returns:
            The processed event or None
        """
        pass

    @property
    @abstractmethod
    def priority(self) -> int:
        """Middleware priority (higher numbers execute first)."""
        pass


class EventPipelineInterface(ABC, Generic[E]):
    """Interface for event processing pipelines."""

    @abstractmethod
    def add_stage(self, stage: EventProcessorInterface[E], priority: int = 0) -> None:
        """Add a processing stage to the pipeline."""
        pass

    @abstractmethod
    def remove_stage(self, stage: EventProcessorInterface[E]) -> None:
        """Remove a processing stage from the pipeline."""
        pass

    @abstractmethod
    def process_through_pipeline(self, event: E) -> Optional[E]:
        """Process an event through all stages in the pipeline."""
        pass


class EventChainInterface(ABC, Generic[E]):
    """Interface for chainable event processors."""

    @abstractmethod
    def set_next(
        self, next_processor: "EventChainInterface[E]"
    ) -> "EventChainInterface[E]":
        """Set the next processor in the chain."""
        pass

    @abstractmethod
    def handle(self, event: E) -> Optional[E]:
        """Handle the event and pass to the next processor if appropriate."""
        pass
